package tsou.cn.threadtest;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 创建一个大小无限的线程池。此线程池支持定时以及周期性执行任务的需求。
 */
public class NewScheduledThreadPoolActivity extends AppCompatActivity implements View.OnClickListener {

    /**
     * 开始
     */
    private Button mStart;
    private ScheduledExecutorService scheduledThreadPool;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_btn);
        initData();
        initView();
    }

    private void initData() {
        scheduledThreadPool = Executors.newScheduledThreadPool(3);
    }

    private void initView() {
        mStart = (Button) findViewById(R.id.start);
        mStart.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
            case R.id.start:
//                initPoolOne();
//                initPoolTwo();
                initPoolThree();
                break;
        }
    }

    /**
     * 表示延迟2秒后每3秒执行一次
     */
    private void initPoolThree() {
        scheduledThreadPool.scheduleWithFixedDelay(new Runnable() {
            @Override
            public void run() {
                if (scheduledThreadPool.isShutdown()) {
                    return;
                }
                Log.e("huangxiaoguo", "huangxiaoguo");
            }
        }, 2, 3, TimeUnit.SECONDS);
    }

    /**
     * 表示延迟2秒后每3秒执行一次
     */
    private void initPoolTwo() {
        scheduledThreadPool.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                if (scheduledThreadPool.isShutdown()) {
                    return;
                }
                Log.e("huangxiaoguo", "huangxiaoguo");
            }
        }, 2, 3, TimeUnit.SECONDS);
    }

    /**
     * 表示延迟2秒后执行
     */
    private void initPoolOne() {
        scheduledThreadPool.schedule(new Runnable() {
            @Override
            public void run() {
                if (scheduledThreadPool.isShutdown()) {
                    return;
                }
                Log.e("huangxiaoguo", "huangxiaoguo");
            }
        }, 2, TimeUnit.SECONDS);
    }

    /**
     * 停止线程工作
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        //threadPool 不能为空 threadPool 没有崩溃 threadPool 没有停止
        if (scheduledThreadPool != null && !scheduledThreadPool.isShutdown()
                &&!scheduledThreadPool.isTerminated()) {
            scheduledThreadPool.shutdownNow();
        }
    }
}
